浏览量 4311
2014/02/04 18:15
switch中的 default 语句不管放在哪个位置,都是在所有case都不满足的情况下最后执行。
foreach语句 for(元素类型 元素变量;遍历对像) 变量元素.draw()即 遍历对象.draw();foreach即for每一个。
for (Shap shp: s)
shp.draw();
个人理解,当 s[0]=gen.next();时
调用RandomShapeGenerator 中的next方法,执行语句case0-2其中一个return语句得到指向Circle Square Triangle 其中的一个引用,并将其以Shape类型发送出去。此例中当return语句指向Circle时 shp.draw() 即将shp元素变量替换为Circle对象,调用Shap类型 Circle对象draw 方法。
package javahaonan.shape;
public class Shape {
public void draw() {}
public void erase() {}
}
package javahaonan.shape;
import static javahaonan.Print.*;
public class Circle extends Shape {
public void draw() { print ("Circle。draw()");}
public void erase() {print ("Cricle.erase()");}
}
package javahaonan.shape;
import static javahaonan.Print.*;
public class Square extends Shape {
public void draw(){print("Square.draw()");}
public void erase(){print("Square.erase()");}
}
package javahaonan.shape;
import static javahaonan.Print.*;
public class Triangle extends Shape {
public void draw(){print("Trinagle.draw()");}
public void erase(){print("Trinagle.erase()");}
}
package javahaonan.shape;
import java.util.*;
public class RandomShapeGenerator {
private Random rand = new Random();
public Shape next(){
switch(rand.nextInt(3)){
default:
case 0:return new Circle();
case 1:return new Square();
case 2:return new Triangle();
}
}
}
package javahaonan.shape;
public class Shapes {
private static RandomShapeGenerator gen = new RandomShapeGenerator();
public static void main(String[] args) {
Shape[] s=new Shape[9];
for (int i=0;i
s[i]=gen.next();
for(Shape shp: s)
shp.draw();
}
}/output*
Square.draw()
Trinagle.draw()
Square.draw()
Circle。draw()
Square.draw()
Trinagle.draw()
Trinagle.draw()
Trinagle.draw()
Trinagle.draw()
*/
上一篇 搜索 下一篇